﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Drawing;
using OpenCvSharp;
using System;
using System.Drawing;
using System.Windows.Forms;
using Size = System.Drawing.Size;
using Point = System.Drawing.Point;
using System.Security.Cryptography;
using OpenCvSharp.Extensions;


namespace PointAsLine
{
    internal class PngLine
    {

        public static void RedImg()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() != DialogResult.OK)
                return;

            PngLineForm form = new PngLineForm(ofd.FileName);
            form.Show();
            
        }
    }

    public partial class PngLineForm : Form
    {
        // 全局变量
        private Mat srcImage;      // 原始图像
        private Mat edgesImage;    // 边缘检测结果
        private Mat displayImage;  // 显示用的图像（带边缘叠加）

        private Image sourceImage;
        private Image sourceImage2;

        // TrackBar 控件绑定的变量
        private int threshold1 = 30;
        private int threshold2 = 154;
        private int threshold3 = 154;
        private int rho = 2;
        PictureBox pictureBox;
        public PngLineForm(string img)
        {
            sourceImage=Image.FromFile(img);
            InitializeComponent();
            InitializeTrackBars();
            LoadImage(img); // 替换为你的图片路径
        }

        private void InitializeComponent()
        {
            this.Text = "Canny Edge Detector";
            this.Size = new Size(1224, 1224);

            CreateScoller(new Point(10, 10),new Point(0,300), "Threshold1", threshold1, (s2,e2) => { threshold1 = (int)s2; });
            CreateScoller(new Point(10,50), new Point(0, 300), "Threshold2", threshold2, (s2, e2) => { threshold2 = (int)s2; });
            CreateScoller(new Point(300, 10), new Point(1, 5), "rho", rho, (s2, e2) => { rho = (int)s2; });
            CreateScoller(new Point(300, 50), new Point(0, 300), "threshold3", threshold2, (s2, e2) => { threshold2 = (int)s2; });

            // 创建 PictureBox 显示图像
            pictureBox = new PictureBox
            {
                Location = new Point(20, 100),
                Size = new Size(1024, 1024),
                SizeMode = PictureBoxSizeMode.Zoom
            };
            this.Controls.Add(pictureBox);

            // 绑定 PictureBox 的图像更新事件
            pictureBox.Paint += (sender, e) =>
            {
                if (displayImage != null)
                {
                    // 将 OpenCvSharp 的 Mat 转换为 Bitmap 并绘制
                    using (Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(displayImage))
                    {
                        e.Graphics.DrawImage(bitmap, 0, 0, pictureBox.Width, pictureBox.Height);
                    }
                }
                e.Graphics.Clear(Color.White);
                e.Graphics.DrawImage(sourceImage, new PointF());
                if (sourceImage2 != null)
                {
                    e.Graphics.DrawImage(sourceImage2, new PointF());
                }
                if (lines != null)
                {
                    for (var i = 0; i < lines.Length; i++)
                    {
                        e.Graphics.DrawLine(Pens.Red, new PointF(lines[i].P1.X, lines[i].P1.Y), new PointF(lines[i].P2.X, lines[i].P2.Y));
                    }
                }
                
            };
        }

        private void CreateScoller(Point location, Point minMax,string desc,int defaultValue,EventHandler onSetValue)
        {
            // 创建标签
            Label label1 = new Label
            {
                Location = new Point(location.X + 200, location.Y),
                Text = desc + $": {defaultValue}",
                Size = new Size(100, 50)
            };
            // 创建 TrackBar 控件
            System.Windows.Forms.TrackBar trackBar1 = new System.Windows.Forms.TrackBar
            {
                Location = location,
                Width = 180,
                Minimum = minMax.X,
                Maximum = minMax.Y,
                Value = defaultValue
            };
            trackBar1.Scroll += (sender, e) =>
            {
                onSetValue(trackBar1.Value, null);
                ((sender as TrackBar).Tag as Label).Text = desc + $": {trackBar1.Value}";
                UpdateEdgeDetection2();
            };
            trackBar1.Tag= label1;

            this.Controls.Add(trackBar1);
            this.Controls.Add(label1);
        }

        private void InitializeTrackBars()
        {
            // TrackBar 的初始值已在构造函数中设置
        }

        private void LoadImage(string imagePath)
        {
            // 加载图像
            srcImage = Cv2.ImRead(imagePath, ImreadModes.Grayscale);
            if (srcImage.Empty())
            {
                MessageBox.Show("无法加载图像！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            // 初始化边缘检测结果
            edgesImage = new Mat();
            UpdateEdgeDetection2();

            // 触发一次 PictureBox 的重绘
            this.Invalidate();
        }

        private LineSegmentPoint[] lines;

        private void UpdateEdgeDetection2()
        {
            // 2. 边缘检测（Canny算法）
            Mat edges = new Mat();
            Cv2.Canny(srcImage, edges, threshold1, threshold2);  // 调整阈值以优化边缘检测

            sourceImage2=BitmapConverter.ToBitmap(edges);

            // 3. 霍夫线变换（检测直线）
            lines = Cv2.HoughLinesP(
                edges,
                rho,                  // rho: 距离分辨率（像素）
                Math.PI / 360,      // theta: 角度分辨率（弧度）
                200,                // threshold: 投票阈值（线段被检测到的最小投票数）
                40,                 // minLineLength: 最小线段长度（小于此值会被忽略）
                10                  // maxLineGap: 同一直线上点之间的最大间隙（允许连接断开的线段）
            );
            pictureBox.Refresh();
        }
    }

}